package com.sndscl.rpc.call;

import com.sndscl.rpc.common.dto.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;

import java.util.concurrent.SynchronousQueue;

/**
 * @Description
 * @Author lsh
 * @Date 2020/10/23 16:41
 **/
public class ResponseHandler extends SimpleChannelInboundHandler<RpcResponse> {

    public NettyClient nettyClient;

    public ResponseHandler(NettyClient nettyClient){
        this.nettyClient = nettyClient;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcResponse rpcResponse) throws Exception {
        if(rpcResponse != null){
            if("00".equals(rpcResponse.getType())){
                return;
            }
            String id = rpcResponse.getId();
            SynchronousQueue synchronousQueue = SndSclCall.synchronousQueueMap.get(id);
            if(synchronousQueue != null){
                synchronousQueue.put(rpcResponse);
            }
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress()+" 连接成功！");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //在服务端关闭时触发此事件
        System.out.println(ctx.channel().remoteAddress()+" 关闭了此连接");
        ctx.close();
        nettyClient.shutdown();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent){
            switch (((IdleStateEvent) evt).state()){
                case READER_IDLE:
                    break;
                case WRITER_IDLE:
                    break;
                case ALL_IDLE:
                    //重连
                    nettyClient.timeOutReConnection();
                    break;
                default:
                    break;
            }
        }
    }

}
